package com.zm.demo.core.leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.lang.System.out;

/**
 * 根据字符出现频率排序
 * @author zoum
 * @create 2020/1/9 15:16
 */
public class FrequencySort {


    public String frequencySort(String s) {
        if (s == null || s.length() == 0){
            return s;
        }

        Map<Character,Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            Character _this = s.charAt(i);
            if (map.get(_this)== null){
                map.put(_this,1);
            }else {
                map.compute(_this, (k, v)->v+1);
            }
        }

        StringBuilder sb = new StringBuilder();
        map.entrySet().stream().sorted((o1,o2)->o2.getValue().compareTo(o1.getValue())).forEach(o -> {
            for (int i = 0; i < o.getValue(); i++) {
                sb.append(o.getKey());
            }
        });
        return sb.toString();
    }

    public static void main(String[]args){
        out.println(new FrequencySort().frequencySort(""));
    }
}
